﻿using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

namespace BF
{
    public static class MultiLanguageUtil
    {
        public static string language { get; private set; }

        /// <summary>
        /// 所有文案的字典
        /// </summary>
        private static readonly Dictionary<int, string> _dict = new Dictionary<int, string>();

        public static IReadOnlyCollection<int> Keys => _dict.Keys;

        public static IReadOnlyCollection<string> Values => _dict.Values;

        public static IReadOnlyDictionary<int, string> Dictionary => _dict;

        public static void InitLanguage(string language)
        {
            MultiLanguageUtil.language = language;
            LoadLanguageConfig();
        }

        private static void LoadLanguageConfig()
        {
            string path = $"Language/{language}";
            TextAsset textAsset = Resources.Load<TextAsset>(path);
            Read(textAsset.bytes);
            Resources.UnloadAsset(textAsset);
        }

        private static void Read(byte[] content)
        {
            string oldSJ = "\\t";
            string newSJ = "\u3000";
            string oldHH = "\\n";
            string newHH = "\n";
            // CSV文案key-value分割符
            char STX = (char)0x02;
            // CSV换行符
            string[] SEP = new string[] { "\r\n" };


            _dict.Clear();
            string txt = Encoding.UTF8.GetString(content);
            string[] rows = txt.Split(SEP, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < rows.Length; ++i)
            {
                string[] cols = rows[i].Split(STX);
                _dict.Add(int.Parse(cols[0]), cols[1].Replace(oldSJ, newSJ).Replace(oldHH, newHH));
            }
        }

        public static string Get(int key)
        {
            if (!_dict.TryGetValue(key, out string value))
            {
                Debug.LogWarning("Key not exits:" + key);
                return string.Empty;
            }
            return value;
        }

        public static bool HasKey(int key)
        {
            return _dict.ContainsKey(key);
        }

        public static void Clear()
        {
            _dict.Clear();
        }
    }
}